package cn.bestick.weightrecord.service;

import cn.bestick.weightrecord.dao.RecordDao;
import cn.bestick.weightrecord.dto.DataWrapper;
import cn.bestick.weightrecord.model.Record;
import cn.bestick.weightrecord.model.User;
import cn.bestick.weightrecord.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * User: Bestick
 * Date: 2016/7/8
 * Time: 18:49
 * Url: http://www.bestick.cn
 * Copyright © 2015-2016 Bestick All rights reserved
 * -----------------------------------------------------------
 * 会当凌绝顶，一览众山小。
 */
@Service
public class RecordService {

    @Autowired
    private RecordDao recordDao;

    /**
     * 增加一条记录
     *
     * @param record 入参
     * @return DataWrapper
     */
    public DataWrapper addRecord(User currentUser, Record record) {
        DataWrapper dataWrapper = new DataWrapper();
        try {
            if(record.getUserId() == null || currentUser == null || !record.getUserId().equals(currentUser.getUserId())) {
                dataWrapper.setStatus(-1);
                dataWrapper.setMsg("添加失败，请重新登录后重试");
                return dataWrapper;
            }
            if (recordDao.getRecordByDate(DateUtil.getCurrentDateStr("yyyy-MM-dd"), record.getUserId())) {
                dataWrapper.setStatus(-1);
                dataWrapper.setMsg("您今天已经添加过一条记录啦，请勿重复添加");
                return dataWrapper;
            }
            recordDao.addRecord(record);
            dataWrapper.setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            dataWrapper.setStatus(-2);
            dataWrapper.setMsg("添加失败：" + e.getMessage());
        }
        return dataWrapper;
    }
}
